<?php

class Application_Model_CarMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Car');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Car $car){
	
		
	
		$vehicleMapper = new Application_Model_VehicleMapper();
		$row = $vehicleMapper->save($car);
		$car->setVehicleId($row);
	
		$data = array(
				'id_vehicle' 		=> $car->getVehicleId(),
				'energy'			=> $car->getEnergy(),
				'transmission'		=> $car->getTransmission(),
		);
	
		if (null === ($id = $car->getCarId())) {
			unset($data['id_car']);
			return $this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_car = ?' => $id));
			return $id;
		}
	}
	
	public function find($id, Application_Model_Car $car)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$car->setCarId($row->id_car);
		$car->setVehicleId($row->id_vehicle);
		$car->setEnergy($row->energy);
		$car->setTransmission($row->transmission);
	
		$vehicleMapper = new Application_Model_VehicleMapper();
		$car = $vehicleMapper->find($car->getVehicleId(), $car);
	
		return $car;
	}
	
	public function delete($id)
	{
	
		$car= new Application_Model_Car();
		$vehicleMapper = new Application_Model_VehicleMapper();
		$car = $this->find($id, new Application_Model_Car());
	
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_car = ?' => $id));
		}
	
		$vehicleMapper->delete($car->getVehicleId());
	
	
	}
	
	public function indexBuilder(Zend_Search_Lucene_Document $doc, Application_Model_Car $car)
	{
		$vehicleMapper = new Application_Model_VehicleMapper();
		$doc->addField(Zend_Search_Lucene_Field::Text('energy', $car->getEnergy(), 'utf-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('transmission', $car->getTransmission(), 'utf-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('objectType', 'car', 'utf-8'));
		$doc = $vehicleMapper->indexBuilder($doc, $car);
		
		return $doc;
	}
}